package com.bluestone.ognl;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import ognl.OgnlContext;
import ognl.OgnlException;

import com.bluestone.util.ClearableValueStack;
import com.bluestone.util.CompoundRoot;
import com.bluestone.util.MemberAccessValueStack;
import com.bluestone.util.ValueStack;
import com.bluestone.ognl.OgnlUtil;
import com.bluestone.BaseAction;
import com.bluestone.BluestoneException;




public class OgnlValueStack implements Serializable, ValueStack,
		ClearableValueStack, MemberAccessValueStack {

    CompoundRoot root;
    transient Map<String, Object> context;
    Class defaultType;
    Map<Object, Object> overrides;
    transient OgnlUtil ognlUtil;
    transient SecurityMemberAccess securityMemberAccess;
    private static final String MAP_IDENTIFIER_KEY = "com.bluestone.ognl.OgnlValueStack.MAP_IDENTIFIER_KEY";    
    
	public String findString(String expr) {
		 return (String) findValue(expr, String.class);
	}

	public String findString(String expr, boolean throwExceptionOnFailure) {
		 return (String) findValue(expr, String.class, throwExceptionOnFailure);
	}

	public Object findValue(String expr) {
        return findValue(expr, false);
	}

	public Object findValue(String expr, boolean throwExceptionOnFailure) {
        try {
            if (expr == null) {
                return null;
            }

            if ((overrides != null) && overrides.containsKey(expr)) {
                expr = (String) overrides.get(expr);
            }

            if (defaultType != null) {
                return findValue(expr, defaultType);
            }

            Object value = ognlUtil.getValue(expr, context, root);
            if (value != null) {
                return value;
            } else {
                checkForInvalidProperties(expr, throwExceptionOnFailure, throwExceptionOnFailure);
                return findInContext(expr);
            }
        } catch (OgnlException e) {
            checkForInvalidProperties(expr, throwExceptionOnFailure, throwExceptionOnFailure);

            return findInContext(expr);
        } catch (Exception e) {
            if (throwExceptionOnFailure)
                throw new BluestoneException(e);

            return findInContext(expr);
        }
	}

	public Object findValue(String expr, Class asType) {
		return findValue(expr, asType, false);
	}

	public Object findValue(String expr, Class asType,
			boolean throwExceptionOnFailure) {
        try {
            if (expr == null) {
                return null;
            }

            if ((overrides != null) && overrides.containsKey(expr)) {
                expr = (String) overrides.get(expr);
            }

            Object value = ognlUtil.getValue(expr, context, root, asType);
            if (value != null) {
                return value;
            } else {
                checkForInvalidProperties(expr, throwExceptionOnFailure, throwExceptionOnFailure);
                return findInContext(expr);
            }
        } catch (OgnlException e) {
            checkForInvalidProperties(expr, throwExceptionOnFailure, throwExceptionOnFailure);
            return findInContext(expr);
        } catch (Exception e) {
            if (throwExceptionOnFailure)
                throw new BluestoneException(e);
            
            return findInContext(expr);
        }
	}

    /**
     * This method looks for matching methods/properties in an action to warn the user if
     * they specified a property that doesn't exist.
     *
     * @param expr the property expression
     */
    private void checkForInvalidProperties(String expr, boolean throwExceptionPropNotFound, boolean throwExceptionMethodFound) {
        if (expr.contains("(") && expr.contains(")")) {

            if (throwExceptionMethodFound)
                    throw new BluestoneException("Could not find method [" + expr + "]");
        } else if (findInContext(expr) == null) {
            // find objects with Action in them and inspect matching getters
            Set<String> availableProperties = new LinkedHashSet<String>();
            for (Object o : root) {
                if (o instanceof BaseAction || o.getClass().getSimpleName().endsWith("Action")) {
                    try {
                        findAvailableProperties(o.getClass(), expr, availableProperties, null);
                    } catch (IntrospectionException ise) {
                        // ignore
                    }
                }
            }
            if (!availableProperties.contains(expr)) {

                if (throwExceptionMethodFound)
                    throw new BluestoneException("Could not find property [" + expr + "]");
            }
        }
    }
   
    /**
     * Look for available properties on an existing class.
     *
     * @param c                   the class to search on
     * @param expr                the property expression
     * @param availableProperties a set of properties found
     * @param parent              a parent property
     * @throws IntrospectionException when Ognl can't get property descriptors
     */
    private void findAvailableProperties(Class c, String expr, Set<String> availableProperties, String parent) throws IntrospectionException {
        PropertyDescriptor[] descriptors = ognlUtil.getPropertyDescriptors(c);
        for (PropertyDescriptor pd : descriptors) {
            String name = pd.getDisplayName();
            if (parent != null && expr.contains(".")) {
                name = expr.substring(0, expr.indexOf(".") + 1) + name;
            }
            if (expr.startsWith(name)) {
                availableProperties.add((parent != null) ? parent + "." + name : name);
                if (expr.equals(name)) break; // no need to go any further
                if (expr.contains(".")) {
                    String property = expr.substring(expr.indexOf(".") + 1);
                    // if there is a nested property (indicated by a dot), chop it off so we can look for method name
                    String rawProperty = (property.contains(".")) ? property.substring(0, property.indexOf(".")) : property;
                    String methodToLookFor = "get" + rawProperty.substring(0, 1).toUpperCase() + rawProperty.substring(1);
                    Method[] methods = pd.getPropertyType().getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.getName().equals(methodToLookFor)) {
                            availableProperties.add(name + "." + rawProperty);
                            Class returnType = method.getReturnType();
                            findAvailableProperties(returnType, property, availableProperties, name);
                        }
                    }

                }
            }
        }
    }
    
    private Object findInContext(String name) {
        return getContext().get(name);
    }
    
	public Map<String, Object> getContext() {
        return context;
	}

	public Map<Object, Object> getExprOverrides() {
        return this.overrides;
	}

	public CompoundRoot getRoot() {
        return root;
	}

	public Object peek() {
        return root.peek();
	}

	public Object pop() {
        return root.pop();
	}

	public void push(Object o) {
        root.push(o);

	}

	public void set(String key, Object o) {
        //set basically is backed by a Map
        //pushed on the stack with a key
        //being put on the map and the
        //Object being the value

        Map setMap = null;

        //check if this is a Map
        //put on the stack  for setting
        //if so just use the old map (reduces waste)
        Object topObj = peek();
        if (topObj instanceof Map
                && ((Map) topObj).get(MAP_IDENTIFIER_KEY) != null) {

            setMap = (Map) topObj;
        } else {
            setMap = new HashMap();
            //the map identifier key ensures
            //that this map was put there
            //for set purposes and not by a user
            //whose data we don't want to touch
            setMap.put(MAP_IDENTIFIER_KEY, "");
            push(setMap);
        }
        setMap.put(key, o);
	}

	public void setDefaultType(Class defaultType) {
        this.defaultType = defaultType;

	}

	public void setExprOverrides(Map<Object, Object> overrides) {
        if (this.overrides == null) {
            this.overrides = overrides;
        } else {
            this.overrides.putAll(overrides);
        }
	}

	public void setValue(String expr, Object value) {
        setValue(expr, value, false);

	}

	public void setValue(String expr, Object value,
			boolean throwExceptionOnFailure) {
        Map<String, Object> context = getContext();

        try {
            context.put(REPORT_ERRORS_ON_NO_PROP, (throwExceptionOnFailure) ? Boolean.TRUE : Boolean.FALSE);
            ognlUtil.setValue(expr, context, root, value);
        } catch (OgnlException e) {
            String msg = "Error setting expression '" + expr + "' with value '" + value + "'";
            if (throwExceptionOnFailure) {
                throw new BluestoneException(msg, e);
            }
        } catch (RuntimeException re) { //XW-281
            if (throwExceptionOnFailure) {
                StringBuilder msg = new StringBuilder();
                msg.append("Error setting expression '");
                msg.append(expr);
                msg.append("' with value ");

                if (value instanceof Object[]) {
                    Object[] valueArray = (Object[]) value;
                    msg.append("[");
                    for (int index = 0; index < valueArray.length; index++) {
                        msg.append("'");
                        msg.append(valueArray[index]);
                        msg.append("'");

                        if (index < (valueArray.length + 1))
                            msg.append(", ");
                    }
                    msg.append("]");
                } else {
                    msg.append("'");
                    msg.append(value);
                    msg.append("'");
                }

                throw new BluestoneException(msg.toString(), re);
            } else {

            }
        } finally {
            context.remove(REPORT_ERRORS_ON_NO_PROP);
        }

	}

	public int size() {
		 return root.size();
	}

	public void clearContextValues() {
		((OgnlContext)context).getValues().clear();

	}

	public void setAcceptProperties(Set<Pattern> acceptedProperties) {
		securityMemberAccess.setAcceptProperties(acceptedProperties);

	}

	public void setExcludeProperties(Set<Pattern> excludeProperties) {
		securityMemberAccess.setExcludeProperties(excludeProperties);

	}

}
